'''
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place and use only constant extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
'''

class Solution:
    
    #数组倒序
    def reverse(self,i,j,nums):
        while(i<j):
            temp = nums[i]
            nums[i] = nums[j]
            nums[j] = temp
            i +=1
            j -=1
    
    
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        
        k=len(nums)-2
        #从后往前，看是否出现前一个小于后一个，没有则继续遍历
        while k>=0 and nums[k]>=nums[k+1]:
            k -=1
        
        #k为-1，则表示原数组为降序数组
        if k==-1:
            #进行反转
            Solution().reverse(0,len(nums)-1,nums)
            return 
        
        #k不为-1，表示中间出现有：前一个小于后一个的情况
        for i in range(len(nums)-1,k,-1):
            #将这个数和最后一个数进行互换位置
            if nums[i]>nums[k]:
                temp = nums[i]
                nums[i] = nums[k]
                nums[k] = temp
                #跳出循环
                break
        #将从第k+1个位置到最后一个位置之间的元素进行倒序
        Solution().reverse(k+1,len(nums)-1,nums)
        